/**
 * Created by wangjunfei on 2017/2/7.
 */
// 路径配置相关
export let siteUrl = '/geminirest'	// 后台服务root
export let htmlUrl = '/geminihtml'	// 前端服务root
export let fileserver = '/geminifs'	// 文件服务名
export let pathConfig = {
  ATTACH_VIEW : htmlUrl + '/module/attach.html'
}

export const con_url = location.href.split('/module')[0]

//无图片时显示默认图片
export  let image_not_foud_data ='http://171.34.169.249:8100/fileserver_install/none.jpg ';

export let getLocationSearch = (name) => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', "i")
  let s = window.location.search.substr(1).match(reg)
  if (s != null) {
    return unescape(s[2])
  }
  return null
}

export let  getTimeStamp =(dateStr)=>{
  let timeStamp =  Date.parse(dateStr.replace(/-/gi,'/'));
  let now = new Date().getTime()
  let diffValue = now - timeStamp
  let minute = 1000*60
  let hour = minute*60
  let day = hour*24
  let month = day*30
  let monthc = diffValue/month
  let weekc = diffValue/(7*day)
  let dayc = diffValue/day
  let hourc = diffValue/hour
  let minc = diffValue/minute
  let result
  if(monthc >=1){
    result = parseInt(monthc) + '个月前'
  }
  else if(weekc >=1){
    result = parseInt(weekc) + '周前'
  }
  else if(dayc >=1){
    result = parseInt(dayc) + '天前'
  }
  else if(hourc >=1){
    result = parseInt(hourc) + '小时前'
  }
  else if(minc >=1){
    result = parseInt(minc) + '分钟前'
  } else {
    result = '刚刚发表'
  }
  return result
}

export let sendRequest = (vueObj,url,item,page,successFn) => {
  let argObj
  if(page!==undefined){
    argObj = {flowGroup:item,page : page}
  }
  else{
    argObj = {flowGroup:item}
  }
  vueObj.$http.post(url,argObj).then(successFn);
}


let $gsafety = (function(window){
  var noticeFn = function(){
    if('undefined' ==typeof comm_app){
      console.warn('请在GsafetyApp中调用接口')
      return false;
    }
    return true;
  }

  return {
    // 选择一个图片
    chooseImage: function(data, callback) {
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.chooseImageCallback = function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.chooseImage(JSON.stringify(data));
    },
    // 选择一个文件
    chooseDoc:function(data, callback){
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.choosefileCallback = function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.chooseDoc();
    },
    // 上传一个文件
    uploadImage: function(data, callback){
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.uploadImageCallback =function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.uploadImage(JSON.stringify(data));
    },
    // 上传一个文件doc
	uploadFile:function(data, callback){
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.uploadImageCallback =function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.uploadFile(JSON.stringify(data));
    },
    // 写入缓存
    writeCache: function(data, callback){
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.writeCacheCallback = function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.writeCache(JSON.stringify(data));
    },
    // 读取缓存
    readCache: function(data, callback){
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.readCacheCallback =function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.readCache(JSON.stringify(data));
    },
    // 设置页面头部右上角的按钮显示以及图标(响应事件调用onMenuClick事件)
    setTitleBar : function (data) {
      var fn = noticeFn();
      if(!fn){
        console.warn('setTitleBar data:');
        console.warn(data);
        return;
      };
      comm_app.setTitleBar(JSON.stringify(data));
    },
    // 打开 intent
    openIntent : function (intent, data) {
      var fn = noticeFn();
      if(!fn){
        console.warn('opend intent:' + intent);
        console.warn('opend intent data:');
        console.warn(data);
        return;
      };
      comm_app.openIntent(intent, JSON.stringify(data));
    },
    //打开链接
    openWindow: function (data) {
      var fn = noticeFn();
      if(!fn){
        console.log('open url with location.href:' + data.url);
        location.href = data.url
        return;
      };
      if(!data.actionBarType){
        data.actionBarType=1;
      }
      comm_app.openWindow(JSON.stringify(data));
    },
    //打开intent
    openIntent : function(intent, data){
      var fn = noticeFn();
      if(!fn){
        console.warn('open intent:');
        console.warn(intent);
        console.warn('open intent data:');
        console.warn(data);
        return;
      };
      comm_app.openIntent(intent,JSON.stringify(data));
    },
    /**
     * 关闭当前activity
     */
    closeWindow : function (data) {
      var optStr = '{}'
      if(data){
    	optStr = JSON.stringify(data);
      }	else {
    	console.log('close window with ' + data);
      }
      var fn = noticeFn();
      if(!fn){
        console.log('please close activity in app, callback data:' + optStr);
        history.go(-1);	// 后退到上一个页面
        return;
      };
      if(data){
    	comm_app.closeWindow(optStr);
      } else {
    	comm_app.closeWindow(); // 无参时写法
      }
    },
    //更新设置
    updateSettings: function (data,callback) {
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.updateSettingsCallback = function(res){
        var obj = JSON.parse(res)
        callback(obj)
      };
      comm_app.updateSettings(JSON.stringify(data));
    },
    //加载设置
    loadSettings: function (data,callback) {
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.loadSettingsCallback = function(res){
        callback(JSON.parse(res));
      }
      comm_app.loadSettings(data);
    },
    //底部弹窗
    onMenuClick: function (callback) {
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.onMenuClick = function(){
        callback();
      }
    },
    //页面返回刷新
    translateDataCallback: function (callback) {
      var fn = noticeFn();
      if(!fn){
    	console.info('bind comm_app translateDataCallback : ' + callback)
        return;
      };
      comm_app.translateDataCallback = function(res){
        callback(res)
      }
    },
    openSession: function (team){
	 var fn = noticeFn();
     if(!fn){
       console.info('start comm_app openSession : ' + team)
       return;
     };
     comm_app.openSession(team)
    },
    //底部弹窗
    setTitle: function (title) {
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.setTitle(title)
    },
    //调起第三方导航功能
    startNavigate: function (data) {
      var fn = noticeFn();
      if(!fn){
    	console.debug('开启导航');
    	console.debug('poiname:' + data.poiname);
    	console.debug('lon:' + data.lon);
    	console.debug('lat:' + data.lat);
        return;
      };
      comm_app.startNav(JSON.stringify(data));
    },
    //自动聚焦时调起软键盘，若为开启状态则关闭
    showOrHideSoftInput : function(){
      var fn = noticeFn();
      if(!fn){
        return;
      };
      comm_app.showOrHideSoftInput()
    }
  }
})(window)
//安卓端自带comm_app全局变量
export {$gsafety}

//手机回退按钮
((g) => {
  if('undefined' == typeof comm_app){
    return;
  }
  comm_app.onBackClick = function(){
    let cb = g.onBackclick;
    if(typeof cb =='function'){
      cb();
    }else{
      g.closeWindow();
    }
  }
})($gsafety)

//非VUE页面js的ajax方法
let $ajax = (()=>{
  let xhr = new XMLHttpRequest();
  return {
    get:(url,successFn,errorFn,aysc)=>{
      "use strict";
      aysc=aysc?aysc:false;
      xhr.onreadystatechange = ()=>{
        if(xhr.readyState==4){
          if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
            console.log(xhr.responseText)
            successFn(xhr.responseText)
          }else{
            errorFn(xhr)
          }
        }
      }
      xhr.open("get",url,aysc)
      xhr.send(null)
    },
    post:(url,data,successFn,errorFn,aysc)=>{
      "use strict";
      aysc=aysc?aysc:false;
      xhr.onreadystatechange = ()=>{
        if(xhr.readyState==4){
          if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
            successFn(xhr.responseText)
          }else{
            errorFn(xhr)
          }
        }
      }
      xhr.open("post",url,aysc)
      xhr.send(data)
    }
  }
})()

export {$ajax}


/*和地图iframe通信控制器*/
/*
* frameId--地图的iframe的ID
* */
let messageController = (frameId)=>{
  "use strict";
  let frame = frameId?document.getElementById(frameId):document.getElementsByTagName('iframe')[0];
  let iframeLoaded = false;//iframe是否加载完毕
  let loaded =false;//地图是否加载完毕
  frame.onload = function () {
    iframeLoaded = true;
    window.addEventListener('message',(e)=>{
      let msgObj = e.data;
      if (msgObj.type) {
        switch (msgObj.type) {
          case "mapLoaded"://选中地图上标记的点
            loaded = true;
            break;
          default:
            break;
        }
      }
    })
  }
  return {
    /*
     * type--操作地图的类型  addPoint/centerPoint
     * objList--坐标集
     * */
    sendMessage:(type,objList,callback)=>{
      "use strict";
      let msg = {type:type,data:objList};
      if(!iframeLoaded){
        frame.onload = function () {
          iframeLoaded = true;
          window.addEventListener('message',(e)=>{
            let msgObj = e.data;
            if (msgObj.type) {
              switch (msgObj.type) {
                case "mapLoaded"://选中地图上标记的点
                  loaded = true;
                  frame.contentWindow.postMessage(msg,'*');
                  if(typeof callback =="function"){
                    callback()
                  }
                  break;
                default:
                  break;
              }
            }
          })
        }
      }else{
        frame.contentWindow.postMessage(msg,'*');
        if(typeof callback =="function"){
          callback()
        }
      }
    },
    receiveMessage:(type,callback)=>{
      "use strict";
      window.addEventListener('message',(e)=>{
        let msgObj = e.data;
        if (msgObj.type) {
          switch (msgObj.type) {
            case type://选中地图上标记的点
              callback(msgObj.data);
              break;
            default:
              break;
          }
        }
      })
    }
  }
}
export {messageController}


//历史搜索数据
/*
 * type--自定义数据类型  如:law--法律法规
 * strHistory--搜索关键字
 * */
export let searchHistoryController = ((dataObj)=>{
  "use strict";
  return {
	arrayname : 'array',// 数组名称常量
	/*
	 * 查找一个缓存块，如果没有则创建一个新的并返回
	 */
	getCacheBlock(index, max) {
	  let dataJson = window.localStorage.getItem(index);
	  if(dataJson) {
		console.debug('find block:' + index + ',data:' + dataJson)
	  } else {
		let data = {array:[], max : max ? max : 5};
		dataJson = JSON.stringify(data);
		window.localStorage.setItem(index,dataJson);
		console.debug('create new block:' + index + ",data:" + dataJson)
	  }
	  return JSON.parse(dataJson);
	},
    /*
	 * 自定义JSON字符串 例：{type:'indexhistory',data:'我的',pageUrl:"/matstroage.html/#",....}
	 * 约定所有模块搜索历史记录 type 为‘indexhistory’，模块单个搜索关键字为模块加History，
	 * 例如避难场所type为‘resasylumareaptHistory’
	 * */
    addPageHistory:function(dataObj){
      // 获取存储对象
      let index = dataObj.type;
      if(!dataObj.keyword) {
    	dataObj.keyword = dataObj.pageUrl
      }

      let val = dataObj.keyword
      console.debug('add item:' + index + ',value:' + val);
      let indexhistory = this.getCacheBlock(index);

      // 判断数组长度，比较对象是否重复
      let array = indexhistory[this.arrayname];
      let p = this.containsItem(index, dataObj);
      // 如果是已有元素，删除指定元素元素
      if(p > -1) {
    	array.splice(p, 1);
      }
      array.push(dataObj);

      // 如果制定元素大于特定长度，则移除第一个数据
      if(array.length > indexhistory.max) {
    	array.splice(0, 1);
      }

      window.localStorage.setItem(index,JSON.stringify(indexhistory));
    },
    /*
     *
     */
    getPageHistory:function(index){
      let indexhistory = this.getCacheBlock(index);
      return indexhistory[this.arrayname].reverse();
    },
    /*
     *
     */
    containsItem (index, dataObj) {
      let indexhistory = this.getCacheBlock(index);
      let array = indexhistory[this.arrayname];
      for(let tmp in array) {
    	if(dataObj.keyword == array[tmp].keyword) {
    	  return tmp
    	}
      }
      return -1;
    },
    deleteHistory:function(key){
      window.localStorage.removeItem(key);
    }
  }

})()

/*
* APP端控制页面的全局对象
* */
export let pageController = (()=>{
  "use strict";
  return {
    initOffline:(cb)=>{
      window.offline=(offlineStatus)=>{//APP切换在线离线的时候调用
        "use strict";
        if(typeof cb=='function'){
          cb(offlineStatus);
        }
      }
    }
  }
})()

